<template>
  <div v-if="dialogVisible">
    <el-dialog
      v-model="dialogVisible"
      title="资料设置"
      width="74%"
      draggable
      custom-class="user-info-dialog"
      :align-center="true"
    >
      <el-form>
        <div class="wrap avator">
          <div class="title">设置头像</div>
          <div class="avator-cot">
            <div class="avator-image">
              <img :src="urlResource + formInline.avatarUrl" alt="" />
              <div class="delete" @click="deleteAvatar(formInline.avatarUrl)" v-if="formInline.avatarUrl">
                <el-icon><Delete /></el-icon>
              </div>
            </div>
            <div>
              <Upload
                v-model:file-list="formInline.fileList"
                :prefix-data="AVATAR"
                :multiple="false"
                :show-file-list="false"
                :limit="1"
                height="40px"
                @change="imgHandler"
              >
                <el-button type="primary">选择照片</el-button>
                <template #tip>
                  <div class="el-upload__tip">仅支持JPG,GIF,PNG格式上传，大小不超过1M</div>
                </template>
              </Upload>
              <!-- <el-upload
                v-model:file-list="fileList"
                class="upload-demo"
                action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
                multiple
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :before-remove="beforeRemove"
                :limit="3"
                :on-exceed="handleExceed"
              >
                <el-button type="primary">选择照片</el-button>
                <template #tip>
                  <div class="el-upload__tip">仅支持JPG,GIF,PNG格式上传，大小不超过1M</div>
                </template>
              </el-upload> -->
            </div>
          </div>
        </div>
        <div class="wrap info">
          <div class="title">基本信息</div>
          <div class="info-form">
            <el-form-item label="姓名：">
              <el-input v-model="formInline.name" placeholder="" clearable />
            </el-form-item>
            <!-- <el-form-item label="手机：">
              <el-input v-model="formInline.mobile" placeholder="" clearable />
            </el-form-item> -->
            <el-form-item label="邮箱：">
              <el-input v-model="formInline.email" placeholder="" clearable />
            </el-form-item>
            <!-- <el-form-item label="出生年月：">
              <el-date-picker v-model="formInline.date" type="date" placeholder="" clearable />
            </el-form-item> -->
            <el-form-item label="性别：">
              <el-select v-model="formInline.sex" placeholder="请选择性别" clearable>
                <el-option v-for="item in genderType" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="所在地区：">
              <el-cascader
                v-model="formInline.addressed"
                :options="areaList"
                clearable
                :props="defaultOptions"
                ref="cascaderRef"
              />
            </el-form-item>
            <el-form-item label="我的积分：">
              <el-input disabled v-model="userStore.userInfo.totalIntegral" placeholder="" clearable />
            </el-form-item>
          </div>
        </div>
        <div class="wrap info">
          <div class="title">企业信息</div>
          <div class="info-form">
            <el-form-item label="所属公司" prop="companyId">
              <el-select v-model="formInline.companyId" placeholder="请选择所属公司" clearable @change="changeCompany">
                <el-option v-for="item in companyList" :key="item.name" :label="item.name" :value="item.companyId" />
              </el-select>
            </el-form-item>
            <el-form-item label="所属部门" prop="departmentIdTemp" v-if="formInline.companyId">
              <el-cascader
                v-model="formInline.departmentIdTemp"
                :options="departmentList"
                :props="{ checkStrictly: true, value: 'id', label: 'name', children: 'departmentModels' }"
                clearable
              />
            </el-form-item>
          </div>
        </div>
        <div class="wrap info">
          <div class="title">系统角色</div>
          <div class="info-form">
            <el-form-item label="系统角色：">
              <el-input disabled v-model="listRoleName" placeholder="" clearable />
            </el-form-item>
          </div>
        </div>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveHandler">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, watch } from "vue";
import { deleteFileApi } from "@/api/modules/upload";
import { useUserStore } from "@/stores/modules/user";
import { genderType } from "@/utils/serviceDict";
import { useAddress } from "@/hooks/useAddress";
import Upload from "@/components/Upload/upload.vue";
import { AVATAR } from "@/constants";
import mittBus from "@/utils/mittBus";
//api
import { getDepartment } from "@/api/modules/organization";
import { getCompanyDepart } from "@/api/modules/customer";
import { listAllRole, getUserById, updateUserSetting } from "@/api/modules/sys"; //

// hooks
const userStore = useUserStore();
const { defaultOptions, areaList } = useAddress();
// 变量
let companyList = reactive([]);
let departmentList = ref([]);
const userRoleList = ref([]);
const formInline = ref({
  name: userStore.userInfo.name,
  mobile: userStore.userInfo.mobile,
  email: userStore.userInfo.email,
  sex: userStore.userInfo.sex,
  addressed: userStore.userInfo.addressed || [],
  companyId: "",
  departmentIdTemp: [],
  fileList: [],
  avatarUrl: userStore.userInfo.avatarUrl || ""
});
const urlResource = window?.staticConfig.urlResource;
const dialogVisible = ref(false);
// computed
const listRoleName = computed(() => {
  console.log(userStore.userInfo.userRoleList);
  const arr = userRoleList.value.filter(item => userStore.userInfo.userRoleList.includes(item.id));
  return arr.map(item => item.name).join(",");
});
// 方法
const listAllRoleFn = async () => {
  const { data } = await listAllRole();
  userRoleList.value = data;
};
// 公司
const changeCompany = item => {
  getDepartmentFn({ companyId: item });
  // const companyLists = companyList.find(itm => itm.id === item);
  // drawerProps.value.row.parentCompanyName = companyLists?.name;
};
// 获取全部公司
const getCompanyListFn = async () => {
  const { data } = await getCompanyDepart();
  companyList = data || [];
};
const getDepartmentFn = async params => {
  try {
    const { data } = await getDepartment(params);
    if (data) {
      departmentList.value = data;
    }
  } catch (e) {
    console.log(e);
  }
};
const imgHandler = img => {
  formInline.value.avatarUrl = img[0].path;
};
// 保存
const saveHandler = async () => {
  try {
    await updateUserSetting({
      id: userStore.userInfo.id,
      departmentId: formInline.value.departmentIdTemp.length ? formInline.value.departmentIdTemp.pop() : "",
      mobile: formInline.value.mobile,
      name: formInline.value.name,
      avatarUrl: formInline.value.avatarUrl,
      sex: formInline.value.sex,
      email: formInline.value.email,
      province: formInline.value.addressed[0],
      city: formInline.value.addressed[1],
      district: formInline.value.addressed[2]
    });
    dialogVisible.value = false;
    mittBus.emit("refreshUserInfo");
  } catch (e) {
    console.log(e);
  }
};
const openDialog = () => {
  dialogVisible.value = true;
};
const init = async () => {
  try {
    const { data } = await getUserById({ id: userStore.userInfo.id });
    formInline.value.addressed = data.provinceCode ? [data.provinceCode, data.cityCode, data.districtCode] : [];
    formInline.value.companyId = (data.companyModel && data.companyModel.id) || "";
    formInline.value.departmentIdTemp = (data.departmentModelList && data.departmentModelList.map((item: any) => item.id)) || [];
    formInline.value.name = data.name || "";
    formInline.value.mobile = data.mobile || "";
    formInline.value.email = data.email || "";
    formInline.value.sex = data.sex || "";
    formInline.value.avatarUrl = data.avatarUrl || "";
    getDepartmentFn({ companyId: formInline.value.companyId });
  } catch (e) {
    console.log(e);
  }
};
// watch
watch(
  () => dialogVisible.value,
  val => {
    if (val) {
      init();
    }
  }
);

const deleteAvatar = async (path: string) => {
  await deleteFileApi({ path });
  formInline.value.fileList = [];
  formInline.value.avatarUrl = [];
};

onMounted(() => {
  init();
  getCompanyListFn();
  listAllRoleFn();
});
defineExpose({ openDialog });
</script>
<style lang="scss" scoped>
:deep(.el-dialog) {
  .el-dialog__header {
    box-sizing: border-box;
    height: 72px;
    padding: 0 30px;
    line-height: 72px;
    color: #333333;
    text-align: left;
  }
  .el-dialog__title {
    font-size: 16px;
  }
  .el-dialog__body {
    padding: 20px 40px 0;
  }
}
.wrap {
  margin-bottom: 18px;
  :deep(.upload-box-s) {
    .el-upload {
      justify-content: flex-start;
    }
  }
}
.title {
  margin-bottom: 18px;
  font-size: 16px;
  font-weight: 600;
  color: #333333;
}
.avator-cot {
  display: flex;
  align-items: flex-end;
  .avator-image {
    width: 88px;
    height: 88px;
    margin-right: 20px;
    background: rgb(169 192 219 / 100%);
    position: relative;

    .delete {
      display: none;
      width: 88px;
      height: 88px;
      position: absolute;
      top: 0;
      left: 0;
      opacity: 0.5;
      background: #000;
      text-align: center;
      line-height: 88px;
      font-size: 16px;
      color: rgba(255, 255, 255, 1);

      .el-icon {
        cursor: pointer;
      }
    }
    &:hover {
      .delete {
        display: block;
      }
    }
    img {
      width: 100%;
      height: 100%;
      border-radius: 50%;
    }
  }
}
.info-form {
  display: flex;
  flex-flow: row wrap;
  align-items: center;
  :deep(.el-date-editor) {
    --el-date-editor-width: 100%;
  }
  :deep(.el-form-item) {
    margin-right: 40px;
  }
  :deep(.el-form-item__label) {
    width: 100px;
  }
  :deep(.el-form-item__content) {
    width: 300px;
    .el-select {
      width: 100%;
    }
  }
}
</style>
